<template>
  <div class="enhanced-container">
    <el-card class="main-card">
      <!-- 头部标题 -->
      <template #header>
        <div class="header-title">
          <span class="title-grey">房态 - </span>
          <span>办理预订</span>
        </div>
      </template>

      <!-- 内容区域 -->
      <div class="content-wrapper">
        <!-- 预订信息 -->
        <el-card class="section-card">
          <h2>预订信息</h2>
          <el-form :model="formData" label-width="100px">
            <div class="form-row">
              <el-form-item label="客源信息：" prop="source">
                <el-select
                  v-model="formData.source"
                  placeholder="请选择"
                  style="width: 220px"
                >
                  <el-option label="会员" value="会员" />
                  <el-option label="非会员" value="非会员" />
                </el-select>
              </el-form-item>

              <el-form-item label="订单来源：" prop="origin">
                <el-select
                  v-model="formData.origin"
                  placeholder="门店前台"
                  style="width: 220px"
                >
                  <el-option label="门店前台" value="门店前台" />
                </el-select>
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="预订姓名：" prop="name" required>
                <el-input
                  v-model="formData.name"
                  placeholder="请输入预订姓名"
                  style="width: 220px"
                />
              </el-form-item>

              <el-form-item label="手机号码：" prop="phone">
                <el-input
                  v-model="formData.phone"
                  placeholder="请输入手机号码"
                  style="width: 220px"
                />
              </el-form-item>
            </div>

            <el-form-item label="预订单号（外部）：" prop="externalId">
              <el-input
                v-model="formData.externalId"
                placeholder="请输入预订单号"
                style="width: 460px"
              />
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 房间信息 -->
        <el-card class="section-card">
          <h2>房间信息</h2>
          <el-form :model="formData" label-width="100px">
            <div class="form-row">
              <el-form-item label="入住日期：" prop="checkInDate">
                <el-date-picker
                  v-model="formData.checkInDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>

              <el-form-item label="离店日期：" prop="checkOutDate">
                <el-date-picker
                  v-model="formData.checkOutDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>

              <el-form-item label="入住天数：" prop="nights">
                <el-input
                  v-model="formData.nights"
                  disabled
                  style="width: 100px"
                />
              </el-form-item>
            </div>

            <!-- 房型表格 -->
            <el-table
              :data="roomTypes"
              border
              class="room-table"
              row-key="id"
              @selection-change="handleSelectionChange"
              ref="multipleTableRef"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column label="房型列表" prop="roomTypeName" />
              <el-table-column label="可定数" prop="count" />
              <el-table-column label="门市价" prop="roomTypePrice" />
              <el-table-column label="房间均价" prop="roomTypePrice" />
              <el-table-column label="房间数量">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.quantity"
                    :min="0"
                    :max="row.available"
                    :disabled="row.available === 0"
                  />
                  <span v-if="row.available === 0" class="stock-alert"
                    >(已售罄)</span
                  >
                </template>
              </el-table-column>
              <el-table-column label="排房">
                <template #default="{ row }">
                  <el-input
                    v-model="row.roomNumber"
                    :disabled="row.quantity === 0"
                    placeholder="输入房号"
                    @change="loadNumber(row.roomNumber)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="早餐份数" prop="breakfast">
                <template #default="{ row }">
                  <el-input v-model="row.breakfast" placeholder="请输入" />
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-card>

        <!-- 商户备注 -->
        <el-card class="section-card">
          <h2>商户备注</h2>
          <el-form-item prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="4"
              placeholder="请输入备注信息"
              maxlength="300"
              show-word-limit
              class="remark-input"
            />
          </el-form-item>
        </el-card>
      </div>

      <!-- 客户信息对话框 -->
      <el-dialog
        v-model="dialogVisible"
        title="客户信息确认"
        width="600px"
        :close-on-click-modal="false"
      >
        <el-form label-width="120px">
          <el-form-item label="房型信息：">
            <el-input v-model="selectedRoomType.roomTypeName" disabled />
          </el-form-item>

          <el-form-item label="房间号码：" required>
            <el-input
              v-model="selectedRoomType.roomNumber"
              placeholder="输入房号"
            />
          </el-form-item>

          <el-form-item label="手机号码：" required>
            <el-input v-model="formData.phone" placeholder="请输入手机号码" />
          </el-form-item>

          <el-form-item label="预订姓名：" required>
            <el-input v-model="formData.name" placeholder="请输入姓名" />
          </el-form-item>

          <el-form-item label="证件类型：">
            <el-select
              v-model="formData.idType"
              placeholder="请选择证件类型"
              style="width: 100%"
            >
              <el-option
                v-for="item in idTypeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="证件号码：">
            <el-input
              v-model="formData.idNumber"
              placeholder="请输入证件号码"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleFinalSubmit"
              >确认提交</el-button
            >
          </div>
        </template>
      </el-dialog>

      <!-- 底部操作按钮 -->
      <div class="centered-actions">
        <el-button type="primary" size="large" @click="handleSubmit"
          >确定</el-button
        >
        <el-button size="large" @click="resetForm">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, computed, ref, onMounted } from "vue";
import { ElMessage, ElTable } from "element-plus";
import moment from "moment";
import { useRouter } from "vue-router";
import {
  GetRCRoomTypeList,
  GetIDType,
  InsertStayrecord,
  GetNewRoomType,
} from "@/api/RoomConditionManagement/RoomCM";

interface RoomType {
  id: string;
  roomTypeName: string;
  roomTypePrice: number;
  count: number;
  quantity?: number;
  available?: number;
  roomNumber?: string;
  breakfast?: number;
}

const router = useRouter();
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const roomTypes = ref<RoomType[]>([]);
const dialogVisible = ref(false);
const idTypeOptions = ref<Array<{ id: string; name: string }>>([]);
const selectedRoomType = ref<RoomType>({} as RoomType);
const selectedRoomnum = ref({
  id: "",
  roomTypeName: "",
  roomTypePrice: 0,
  numId: "",
  roomNumName: "",
  count: 0,
});
// 主表单数据
const formData: any = reactive({
  source: "",
  origin: "门店前台",
  name: "",
  phone: "",
  externalId: "",
  checkInDate: moment().format("YYYY-MM-DD"),
  checkOutDate: moment().add(1, "days").format("YYYY-MM-DD"),
  nights: computed(() =>
    moment(formData.checkOutDate).diff(moment(formData.checkInDate), "days")
  ),
  remark: "",
  idType: "",
  idNumber: "",
});

// 初始化加载
onMounted(async () => {
  await loadRoomTypes();
  await loadIDType();
});

// 加载房型数据
const loadRoomTypes = async () => {
  try {
    const res = await GetRCRoomTypeList();
    if (res.code === 200) {
      roomTypes.value = res.data.map((item: any) => ({
        ...item,
        quantity: 0,
        available: item.count,
        breakfast: 0,
        roomNumber: "",
      }));
    }
  } catch (error) {
    ElMessage.error("房型加载失败");
  }
};

// 加载证件类型
const loadIDType = async () => {
  try {
    const res = await GetIDType();
    idTypeOptions.value = res.data;
  } catch (error) {
    ElMessage.error("证件类型加载失败");
  }
};

// 获取房号信息
const loadNumber = async (roomNumber: string) => {
  try {
    const res = await GetNewRoomType(roomNumber);
    console.log("获取房号", res);
    selectedRoomnum.value = res.data;
  } catch (error) {
    ElMessage.error("获取房号信息失败");
  }
};

// 处理表格选择变化
const handleSelectionChange = (selected: RoomType[]) => {
  if (selected.length > 0) {
    selectedRoomType.value = { ...selected[0] };
    // 自动填充第一个选中的房型信息
    roomTypes.value.forEach((row) => {
      if (!selected.some((s) => s.id === row.id)) {
        row.quantity = 0;
        row.breakfast = 0;
        row.roomNumber = "";
      }
    });
  }
};

// 表单验证
const validateForm = () => {
  if (!formData.name.trim()) {
    ElMessage.error("预订姓名不能为空");
    return false;
  }

  const validRooms = roomTypes.value.filter((item) => item.quantity! > 0);
  if (validRooms.length === 0) {
    ElMessage.error("请至少选择一种房型");
    return false;
  }

  const invalidRooms = validRooms.filter(
    (item) => item.quantity! > 0 && !item.roomNumber?.trim()
  );
  if (invalidRooms.length > 0) {
    ElMessage.error("请为选中的房型输入房号");
    return false;
  } else {
  }

  return true;
};

// 提交处理
const handleSubmit = () => {
  if (!validateForm()) return;

  // 获取选中的房型
  const selected = roomTypes.value.filter((t) => t.quantity! > 0);
  if (selected.length === 0) return;

  selectedRoomType.value = { ...selected[0] };
  dialogVisible.value = true;
};

// 最终提交
const handleFinalSubmit = async () => {
  try {
    const payload = {
      ...formData,
      roomType: selectedRoomType.value,
      checkInDays: formData.nights,
    };

    const bookingDTO = {
      sourceinformation: formData.source,
      ordersource: formData.origin,
      reservationname: formData.name,
      reservationcode: formData.externalId,
      checkintime:formData.checkInDate,
      checkouttime:formData.checkOutDate,
      checkindaynum: formData.nights,
      roomtypeid: selectedRoomType.value.id,
      roomtypename: selectedRoomType.value.roomTypeName,
      roomnumberid: selectedRoomnum.value.numId, // 根据实际情况调整
      roomnum: selectedRoomnum.value.roomNumName,
      customertypeid: "3fa85f64-5717-4562-b3fc-2c963f66afa6", // 示例ID，需替换实际值
      customertypename: formData.source === "会员" ? "会员客户" : "散客",
      staystate: 1, // 假设1表示已预订状态
      roomamount: selectedRoomType.value.quantity,
      roomcustomizeprice: selectedRoomType.value.roomTypePrice,
      totalprices: selectedRoomType.value.roomTypePrice * formData.nights,
      idnumberType: Number(formData.idType),
      idnumber: formData.idNumber,
      merchantdesc: formData.remark,
    };

    console.log("提交的预订数据：", bookingDTO);

    InsertStayrecord(bookingDTO)
      .then((res) => {
        console.log("预订成功", res);
        ElMessage.success("预订成功");
        dialogVisible.value = false;
       router.push("/Order/AccommodationOrders/AccommodationRecords");
      })
      .catch((err) => {
        console.error("预订失败", err);
        ElMessage.error("预订失败，请重试");
      });
  } catch (error) {
    ElMessage.error("提交失败，请重试");
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    source: "",
    origin: "门店前台",
    name: "",
    phone: "",
    externalId: "",
    checkInDate: moment().format("YYYY-MM-DD"),
    checkOutDate: moment().add(1, "days").format("YYYY-MM-DD"),
    remark: "",
    idType: "",
    idNumber: "",
  });

  roomTypes.value.forEach((item) => {
    item.quantity = 0;
    item.breakfast = 0;
    item.roomNumber = "";
  });

  multipleTableRef.value?.clearSelection();
};
</script>

<style scoped>
.enhanced-container {
  padding: 20px;
  background: #f5f7fa;
}

.main-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-card {
  margin-bottom: 20px;
}

.section-card h2 {
  font-size: 16px;
  color: #303133;
  margin-bottom: 20px;
}

.form-row {
  display: flex;
  gap: 30px;
  margin-bottom: 20px;
}

.room-table {
  margin-top: 20px;
}

.centered-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.dialog-footer {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  text-align: right;
}

.stock-alert {
  color: #f56c6c;
  margin-left: 10px;
}

.remark-input {
  width: 80%;
}
</style>